package com.ruoyi.user.controller;

import com.ruoyi.common.core.domain.User;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.sms.service.SMSService;
import com.ruoyi.user.domain.LoginRequest;
import com.ruoyi.user.domain.UserResponse;
import com.ruoyi.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户信息管理Controller
 * 
 * @author fxy
 * @date 2024-09-12
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;
    @Autowired
    private SMSService smsService;
    /**
     * 查询用户信息管理列表
     */
    @RequiresPermissions("user:user:list")
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出用户信息管理列表
     */
    @RequiresPermissions("user:user:export")
    @Log(title = "用户信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户信息管理数据");
    }

    /**
     * 获取用户信息管理详细信息
     */
    @RequiresPermissions("user:user:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userService.selectUserById(id));
    }
    @RequiresPermissions("user:user:query")
    @GetMapping(value = "/phone")
    public AjaxResult getInfoByPhone(@RequestParam("phone") String phone)
    {
        System.out.println("phone = " + phone);
        User user = userService.selectUserByPhone(phone);
        System.out.println("user = " + user);
        return AjaxResult.success(user);
    }


    //用户点击获取验证码
    @GetMapping("/getCode")
    //@RequiresPermissions("user:user:query")
    public AjaxResult getCode(@RequestParam("phone") String phone) {
        //获取验证码并设置过期时间
        try {
            //SMSService.sendByUser(phone);
            smsService.sendVerificationCodeByUser(phone);
            return AjaxResult.success("验证码已发送");
        }catch (Exception e){
            return AjaxResult.error("验证码发送失败");
        }
    }

    //登录
//    @RequiresPermissions("user:user:add")
//    @Log(title = "用户信息管理", businessType = BusinessType.INSERT)
//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody User user,@RequestParam("code") String code) {
//        //判断用户输入的验证码和
//    //        return toAjax(userService.insertUser(user));
//        try{
//            //验证码验证
//            boolean isValidCode = userService.verifyCode(user.getPhone(), code);
//            if (!isValidCode) {
//                return AjaxResult.error("验证码无效或已过期");
//            }
//            // 处理登录业务
//            User loggedInUser = userService.insertUser(user);
//            if (loggedInUser == null) {
//                return AjaxResult.error("验证码输入错误");
//            }
//            //生成token
//            String token = generateToken(user.getPhone());
//            return AjaxResult.success(new UserResponse(loggedInUser, token));
//        }catch (Exception e){
//            return AjaxResult.error("登录失败: " + e.getMessage());
//        }
//    }
    // 控制器方法
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginRequest loginRequest) {
        System.out.println("loginRequest = " + loginRequest);
        String phone = loginRequest.getPhone();
        try {
            // 验证码验证
           /* boolean isValidCode = userService.verifyCode(loginRequest.getPhone(), loginRequest.getCode());
            if (!isValidCode) {
                return AjaxResult.error("验证码无效或已过期");
            }*/
            System.out.println("11111");
            // 处理登录业务
            User user = new User(null,phone,null,null,null);
            System.out.println("User to insert = " + user);
            User loggedInUser = userService.insertUser(user);
            System.out.println("Logged in user = " + loggedInUser);
            if (loggedInUser == null) {
                return AjaxResult.error("登录失败");
            }
            // 根据手机号生成 token
            //String token = jwtTokenProvider.generateToken(loggedInUser.getPhone());
            //return AjaxResult.success(new UserResponse(loggedInUser, token));
            String token = generateToken(loggedInUser.getPhone());
            return AjaxResult.success(new UserResponse(loggedInUser, token));
        } catch (Exception e) {
            e.printStackTrace(); // 打印堆栈跟踪
            return AjaxResult.error("登录失败aaa: " + e.getMessage());
        }
    }
    private String generateToken(String phone) {
        // 生成 Token 的逻辑
        return "token-" + phone; // 这里只是示例，实际中应该使用 JWT 或其他安全方法生成 Token
    }
    /**
     * 新增用户信息管理
     */
    @RequiresPermissions("user:user:add")
    @Log(title = "用户信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user)
    {
        return AjaxResult.success(userService.insertUser(user));
    }
    /**
     * 修改用户信息管理
     */
    @RequiresPermissions("user:user:edit")
    @Log(title = "用户信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户信息管理
     */
    @RequiresPermissions("user:user:remove")
    @Log(title = "用户信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }
}
